package com.ray.business.strategy.order.edit;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseMaterialModel;
import com.ray.business.builder.BusinessBuilder;
import com.ray.business.builder.BusinessInBuilder;
import com.ray.business.builder.OrderDeleteIndexBuilder;
import com.ray.business.check.BusinessOutCheck;
import com.ray.business.enums.BusinessStatusEnum;
import com.ray.business.service.*;
import com.ray.business.service.compose.BusinessService;
import com.ray.business.service.compose.IndexService;
import com.ray.business.table.entity.*;
import com.ray.business.table.params.business.BusinessEditParams;
import com.ray.common.BooleanValue;
import com.ray.common.ObjectValue;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.magicBlock.Strategy;
import com.ray.magicBlock.anno.Block;
import com.ray.util.CodeSplitUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 订单商品数据
 * @Class: PurchaseInService
 * @Package com.ray.wms.strategy.in
 * @date 2020/6/8 15:05
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Block(group = "editBusiness", strategy = "in", desc = "工艺商品物料编辑")
public class InOrderEditService implements Strategy<BusinessEditParams, LoginUser, String> {

    @Autowired
    private ProdBusinessService prodBusinessService;
    @Autowired
    private ProdBusinessInService prodBusinessInService;
    @Autowired
    private ProdBusinessOutService prodBusinessOutService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private IndexService indexService;
    @Autowired
    private ProdOrderStepService prodOrderStepService;
    @Autowired
    private ProdStepService prodStepService;
    @Autowired
    private ProdOrderDeleteIndexService prodOrderDeleteIndexService;

    @Override
    public String execute(BusinessEditParams editParams, LoginUser loginUser) {
       // Assert.hasLength(editParams.getEmployee(), "生产人员不能为空");
        BusinessBuilder businessBuilder = new BusinessBuilder();
        businessBuilder.append(editParams).appendEdit(loginUser).appendStatus(BusinessStatusEnum.UN_CHECK.getValue());

        List<String> deleteIndexList = new ArrayList<>();
        //还原对应出库的状态
        prodBusinessInService.listAll(editParams.getBusinessCode(), loginUser).forEach(prodBusinessIn -> {
            //还原数据
            if (StrUtil.isNotBlank(prodBusinessIn.getOutCode())) {
                prodBusinessOutService.cancelBusinessOut(prodBusinessIn.getOutCode(), loginUser);
            }
            if (ObjectUtil.isNotNull(prodBusinessIn.getIndexSort())) {
                deleteIndexList.add(String.valueOf(prodBusinessIn.getIndexSort()));
            }
        });
        //删除原有的记录
        prodBusinessInService.deleteByBusinessCode(editParams.getBusinessCode(), loginUser);
        final List<BigDecimal> quantity = new ArrayList<>();
        final BooleanValue booleanValue = new BooleanValue(false);
        //查询工序是否产品转换
        ProdStep prodStep = prodStepService.queryStepByStepCode(editParams.getStepCode(), loginUser);
        new AbstractCheck<>(prodStep).checkNull("工序不存在");
        ProdOrderStep prodOrderStep = prodOrderStepService.lastStep(CodeSplitUtil.getFirst(editParams.getGoodsCode()), loginUser);
        if (StrUtil.equals(prodOrderStep.getStepCode(), editParams.getStepCode())) {
            //最后一个工序
            booleanValue.setValue(true);
            //查询订单对应的顺序
            editParams.getGoods().forEach(goods -> {
                deleteIndexList.remove(String.valueOf(goods.getIndexSort()));
            });
            List<ProdOrderDeleteIndex> saveIndexList = new ArrayList<>();
            //删除多余的序列号
            deleteIndexList.forEach(value -> {
                log.info("删除的顺序:{}",value);
                saveIndexList.add(new OrderDeleteIndexBuilder().appendOrderNo(editParams.getOrderNo()).appendGoodsCode(CodeSplitUtil.getFirst(editParams.getGoodsCode()))
                        .appendCreate(loginUser).appendIndex(Integer.parseInt(value)).bulid());
            });
            //保存删除的序号
            if (ObjectUtil.isNotEmpty(deleteIndexList)) {
                prodOrderDeleteIndexService.saveBatch(saveIndexList);
            }
        }
        List<String> keys = new ArrayList<>();
        //保存物料明细
        List<ProdBusinessIn> inList = editParams.getGoods().stream().map(businessGoodsParams -> {
            //没有序列号就生成
            if (StrUtil.isBlank(businessGoodsParams.getSerialNumber())) {
                businessGoodsParams.setSerialNumber(businessService.getNumber());
            }
            //没有顺序
            if (ObjectUtil.isNull(businessGoodsParams.getIndexSort())) {
                //生成顺序号
                if (booleanValue.getValue()) {
                    businessGoodsParams.setIndexSort(indexService.queryIndex(editParams.getOrderNo(), CodeSplitUtil.getFirst(editParams.getGoodsCode()), loginUser));
                }
            }
            if (keys.contains(businessGoodsParams.getKey())) {
                log.info("物料重复:{}", JSON.toJSONString(businessGoodsParams));
                throw BusinessExceptionFactory.newException("物料重复");
            }
            BusinessInBuilder businessInBuilder = new BusinessInBuilder().append(businessGoodsParams)
                    .appendBusinessCode(businessBuilder.getCode()).appendOrderNo(editParams.getOrderNo()).appendCreate(loginUser);
            //判断是否关联唯一单号
            if (StrUtil.isNotBlank(businessGoodsParams.getCode())) {
                //查询数据信息
                ProdBusinessOut businessOut = prodBusinessOutService.getUsableGoodsByCode(businessGoodsParams.getCode(), loginUser);
                new BusinessOutCheck(businessOut).checkNull(SysMsgCodeConstant.Error.ERR10000002);
                //更新使用状态
                if (!prodBusinessOutService.useBusinessOut(businessGoodsParams.getCode(), businessOut.getUpdateVersion(), loginUser)) {
                    log.info("更新记录失败:{}", businessGoodsParams.getCode());
                    throw BusinessExceptionFactory.newException("更新记录异常");
                }
                //添加关联
                businessInBuilder.appendOutCode(businessOut.getCode()).appendGangNo(businessOut.getGangNo());
            }
            quantity.add(businessGoodsParams.getQuantity());
            return businessInBuilder.bulid();
        }).collect(Collectors.toList());
        //保存总数
        businessBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //更新
        prodBusinessService.edit(businessBuilder.bulid(), loginUser);
        //保存数据
        prodBusinessInService.saveBatch(inList);

        return businessBuilder.getCode();
    }
}
